package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithDishFlavor(DishDto dishDto) {
        //先保存菜品 dish
        this.save(dishDto);

        // 在保存口味 DishFlavor
        List<DishFlavor> flavors = dishDto.getFlavors();
        //给每个菜品口味设置dishId
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品数据
        Dish dish = this.getById(id);
        //查询口味数据
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dish.getId());
        //得到菜品口味的集合
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

        //合并 dish + dishFlavorList =dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

    @Override
    public void updateByIdWithFlavor(DishDto dishDto) {
        this.getById(dishDto);
        //清理当前菜品所对应的口味
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //添加当前提交的口味数据
        //创建集合存储口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        //将集合中口味数据保存
        dishFlavorService.saveBatch(flavors);
    }
}
